import Config from "./config";
const TokenKey = Config.TokenKey;

export function getToken() {
  let token = localStorage.getItem(TokenKey);
  let remainTime = localStorage.getItem("expires_time") - new Date().getTime();
  let token_type = localStorage.getItem("token_type");
  let bearerToken = token_type + " " + token;
  return token && remainTime > 0 ? bearerToken : false;
}

/**
 * TokenKey token,refresh_token 刷新token,expires_time 刷新时间
 */
export function setToken(tokenInfo) {
  let time = new Date().getTime();
  time += tokenInfo.expires_in * 1000;
  localStorage.setItem(TokenKey, tokenInfo.access_token);
  localStorage.setItem("refresh_token", tokenInfo.refresh_token);
  localStorage.setItem("expires_time", time);
  localStorage.setItem("token_type", tokenInfo.token_type);
}

export function removeToken(opt) {
  localStorage.removeItem(TokenKey);
  localStorage.removeItem("refresh_token");
  localStorage.removeItem("expires_time");
  localStorage.removeItem("token_type");
  sessionStorage.removeItem("searchParams");
}

export function isRefreshToken() {
  let refreshTime = localStorage.getItem("expires_time");
  let refresh_token = localStorage.getItem("refresh_token");
  if (refreshTime && refresh_token) {
    let nowTime = new Date().getTime();
    // 提前十分钟刷新
    if (refreshTime - nowTime < 10 * 60 * 1000 && refreshTime - nowTime > 0) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}
